import { CACHE_KEY, EVENT_TYPE, emitEvent, getCache, setCache } from '@/utils';
import { PlusCircleFilled } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Table,
  Tag,
  Typography,
} from 'antd';
import React from 'react';
import { io } from 'socket.io-client';

const Admin: React.FC = () => {
  const [data, setData] = React.useState(getCache(CACHE_KEY.DOCTOR_RECORD));
  const [row, setActiveRow] = React.useState(null);
  const [medOpen, setMedOpen] = React.useState(false);
  const [avals, setAvals] = React.useState<any>({});

  const [form] = Form.useForm();

  console.log('[data]', data);
  const beginConsultation = (record) => {
    const socket = io('wss://zkapi.lvseguanjia.cn:16064', {
      ackTimeout: 10000,
      retries: 3,
      auth: {
        serverOffset: 0,
      },
      port: 3000,
    });
    const clientOffset = `${socket.id}-${0}`;
    socket.emit(
      EVENT_TYPE.CONSULTATION,
      {
        type: EVENT_TYPE.RE_CONSULTATION,
        name: record.prisoner,
      },
      clientOffset,
    );

    // emitEvent(EVENT_TYPE.CONSULTATION, {
    //   name: record.prisoner,
    // });
  };

  const beginMedicine = () => {
    setMedOpen(false);
    emitEvent(EVENT_TYPE.MEDICINE_CALL, {
      name: row.prisoner,
    });
  };

  const handleOpenMedi = (record) => {
    setActiveRow(record);
    setMedOpen(true);
  };

  const columns = [
    {
      title: '姓名',
      width: 100,
      dataIndex: 'prisoner',
      key: 'prisoner',
    },
    {
      title: '监室',
      width: 100,
      dataIndex: 'room',
      key: 'room',
    },
    {
      width: 100,
      title: '主治医生',
      dataIndex: 'doctor',
      key: 'doctor',
      render: (_) => _ || '暂无',
    },
    {
      title: '自述症状',
      dataIndex: 'prisonerSay',
      key: 'prisonerSay',
      render: (_) => _ || '暂无',
      width: 150,
    },
    {
      title: '诊断',
      dataIndex: 'diagnosis',
      key: 'diagnosis',
      width: 150,
      render: (_) => _ || '暂无',
    },
    {
      title: '自述视频',
      dataIndex: 'video',
      key: 'video',
      width: 130,
      render: (_) => <a>播放自述视频</a>,
    },
    {
      title: '状态',
      dataIndex: 'medicineStatus',
      key: 'medicineStatus',
      render: (_) => <Tag color="green">{_}</Tag>,
    },

    // {
    //   title: '患者自述',
    //   dataIndex: 'prisoner_descrition',
    //   key: 'prisoner_descrition',
    //   render: (_) => _ || '暂无',
    //   width: 100,
    // },
    {
      title: '最后更新',
      dataIndex: 'time',
      key: 'time',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Row gutter={[10, 10]}>
          <Col>
            <Button type="primary" onClick={() => beginConsultation(record)}>
              远程问诊
            </Button>
          </Col>
          <Col>
            <Button type="primary" onClick={() => handleOpenMedi(record)}>
              治疗及处置
            </Button>
          </Col>
          <Col>
            <Button>详情</Button>
          </Col>
        </Row>
      ),
    },
  ];

  const initEvent = () => {
    const socket = io('wss://zkapi.lvseguanjia.cn:16064', {
      ackTimeout: 10000,
      retries: 3,
      auth: {
        serverOffset: 0,
      },
      port: 3000,
    });
    console.log('😈初始化socket');
    // currentSocket.current = socket;

    socket.on(EVENT_TYPE.RE_ADD_DOCTOR_RECORD, (row) => {
      console.log('[row]', row);
      if (data) {
        const newData: any = [...data, row];
        setCache(CACHE_KEY.DOCTOR_RECORD, newData, true);
        setData(newData);
      }
    });
    // onEvent(EVENT_TYPE.ADD_DOCTOR_RECORD, (row) => {
    //   if (data) {
    //     const newData: any = [...data, row];
    //     setCache(CACHE_KEY.DOCTOR_RECORD, newData, true);
    //     setData(newData);
    //   }
    // });
  };

  React.useEffect(() => {
    initEvent();
  }, []);

  return (
    <PageContainer>
      <Modal
        title="治疗及处置"
        open={medOpen}
        // open
        onOk={beginMedicine}
        onCancel={() => setMedOpen(false)}
      >
        <Form
          labelCol={{ span: 6 }}
          form={form}
          onValuesChange={(_, avals) => {
            setAvals(avals);
          }}
        >
          <h3>医生诊断</h3>
          <Form.Item label="诊断" name={'zhenduan'}>
            <Select
              allowClear
              onChange={(e) => {
                if (e)
                  form.setFieldsValue({
                    zhenduan: '扁桃腺化脓',
                    result:
                      '部有黏膜充血、扁桃体有明显的充血肿大，扁桃体表面有化脓点，高热39.4、四肢疼痛',
                    rule: '每次1片 一天3次 3天',
                  });
              }}
            >
              <Select.Option value="扁桃腺化脓">扁桃腺化脓</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label="诊断结果" name={'result'}>
            <Input.TextArea rows={5} placeholder="请输入"></Input.TextArea>
          </Form.Item>

          <Divider></Divider>

          <h3>治疗处置</h3>
          {/* <Form.Item label="药剂">
            <div className="flex-aic">
              <Checkbox.Group>
                <Checkbox>阿莫西林</Checkbox>
              </Checkbox.Group>
              <Checkbox.Group>
                <Checkbox>999感冒灵</Checkbox>
              </Checkbox.Group>
              <Checkbox.Group>
                <Checkbox>布洛芬</Checkbox>
              </Checkbox.Group>
            </div>
          </Form.Item> */}
          {avals?.['zhenduan'] === '扁桃腺化脓' && (
            <div>
              <Card bodyStyle={{ paddingBottom: 0 }}>
                <Form.Item label="药剂">
                  <Input defaultValue={'头孢呋辛酯片'}></Input>
                </Form.Item>
                <Form.Item label="用法">
                  <Input defaultValue={'每次1片 一天3次 3天'}></Input>
                </Form.Item>
              </Card>

              {/* <div className="flex-aic nowrap">
                药剂：<Input defaultValue={'头孢呋辛酯片'}></Input>
              </div>
              <div className="flex-aic nowrap mt10">
                用法：<Input defaultValue={'每次1片 一天3次 3天'}></Input>
              </div> */}
            </div>
          )}
          <div className="flex-center mt10 mb10">
            <PlusCircleFilled size={30} style={{ fontSize: 30 }}></PlusCircleFilled>
          </div>

          {/* <Form.Item label="用法" name={'rule'} className='mt10'>
            <Input defaultValue={''}></Input>
          </Form.Item> */}
          <Divider></Divider>
          <Form.Item label="其他处置">
            <Input.TextArea rows={3} placeholder="请输入诊断信息"></Input.TextArea>
          </Form.Item>
        </Form>
      </Modal>
      <Card>
        <Typography.Title level={2} style={{ textAlign: 'center' }}>
          <Row gutter={[10, 10]}>
            <Col span={6}>
              <Input placeholder="输入区域"></Input>
            </Col>
            <Col span={6}>
              <Input placeholder="输入监室"></Input>
            </Col>
            <Col span={6}>
              <Input placeholder="输入主治医生"></Input>
            </Col>
            <Col span={6}>
              <Select placeholder="选择状态" style={{ width: '100%', textAlign: 'left' }}>
                <Select.Option>未处置</Select.Option>
                <Select.Option>治疗中</Select.Option>
              </Select>
            </Col>
          </Row>
          <div className="flex-bt  mb10">
            <div></div>
            <div>
              <Button type="primary">搜索</Button>
              <Button type="primary" className="ml10">
                导出
              </Button>
              <Button type="primary" className="ml10">
                打印
              </Button>
            </div>
          </div>
          <Table className="mt10" columns={columns} dataSource={data}></Table>
        </Typography.Title>
      </Card>
    </PageContainer>
  );
};

export default Admin;
